package com.wyx.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyx.Common.MyException;
import com.wyx.DTO.SetmealDto;
import com.wyx.Dao.SetmealDao;
import com.wyx.Dao.SetmealDishDao;
import com.wyx.Pojo.Setmeal;
import com.wyx.Pojo.SetmealDish;
import com.wyx.Service.SetmealDishService;
import com.wyx.Service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class SetmealServiceimpl extends ServiceImpl<SetmealDao, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private SetmealDishDao setmealDishDao;
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐
     * @param setmealDto
     */
    @Override
    @Transactional
    public void AddnewSetmeal(SetmealDto setmealDto) {
        //插入到setmeal表种
        setmealDao.insert(setmealDto);
        Long id = setmealDto.getId();
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            //插入到setmeal_dish表中
            setmealDish.setSetmealId(id);
            setmealDishDao.insert(setmealDish);
        }
    }
    //删除套餐信息及套餐菜品表的信息
    @Override
    @Transactional
    public void deleteSetmealanddish(Long[] ids) {
        List<Long> id = Arrays.asList(ids);

        List<Setmeal> setmeals = setmealDao.selectBatchIds(id);
        for (Setmeal setmeal : setmeals) {
            if (setmeal.getStatus() == 1) {
                throw new MyException("当前有套餐正在售卖不能删除");
            }
        }
        //判断没事了就删除套餐表的数据
        setmealDao.deleteBatchIds(id);
        //删除套餐菜品表的数据
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SetmealDish::getSetmealId, id);
        setmealDishDao.delete(wrapper);
    }

    //修改套餐信息及套餐菜品表的信息
    @Override
    public void UpdateSetmealandDish(SetmealDto setmealDto) {
        //修改setmeal表
        setmealDao.updateById(setmealDto);

        //修改setmealDish表
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId, setmealDto.getId());
        //将之前的数据删了
        setmealDishDao.delete(wrapper);
        //新增SetmealDish数据
        setmealDishService.saveBatch(setmealDishes);
    }
}
